// farm/system/SmartFarmSystem.java
package farm.system;

import farm.entity.EnvironmentData;
import farm.entity.FarmMachine;
import farm.pattern.chain.ObstacleHandler;
import farm.pattern.chain.PathAdjustmentHandler;
import farm.pattern.chain.SafetyHandler;
import farm.pattern.command.Command;
import farm.pattern.command.StartCommand;
import farm.pattern.command.StopCommand;
import farm.pattern.factory.ConcreteFarmMachineFactory;
import farm.pattern.factory.FarmMachineFactory;
import farm.pattern.observer.EnvironmentMonitor;

import java.util.*;
import java.util.InputMismatchException;

public class SmartFarmSystem {
    // 菜单常量
    private static final int MENU_VIEW_STATUS = 1;
    private static final int MENU_SIMULATE_ENV = 2;
    private static final int MENU_SEND_COMMAND = 3;
    private static final int MENU_EXIT = 4;

    private static final FarmMachineFactory factory = new ConcreteFarmMachineFactory();
    private static final EnvironmentMonitor monitor = new EnvironmentMonitor();
    private static final List<FarmMachine> machines = new ArrayList<>();
    private static final Scanner scanner = new Scanner(System.in);

    public static void main(String[] args) {
        initSystem();
        try {
            showMenu();
        } finally {
            scanner.close();  // 确保资源释放
        }
    }

    private static void initSystem() {
        // 初始化安全责任链
        SafetyHandler obstacleHandler = new ObstacleHandler();
        SafetyHandler pathHandler = new PathAdjustmentHandler();
        obstacleHandler.setNextHandler(pathHandler);

        // 创建并配置农机（已在实体类初始化状态）
        FarmMachine seeder = factory.createFarmMachine("播种机");
        FarmMachine sprayer = factory.createFarmMachine("喷药机");
        seeder.setSafetyChain(obstacleHandler);
        sprayer.setSafetyChain(obstacleHandler);

        // 注册环境观察者
        monitor.addObserver(seeder);
        monitor.addObserver(sprayer);
        machines.addAll(Arrays.asList(seeder, sprayer));
    }

    private static void showMenu() {
        while (true) {
            System.out.println("\n==== 智能农机管理系统 ====");
            System.out.println(MENU_VIEW_STATUS + ". 查看运行中农机状态");
            System.out.println(MENU_SIMULATE_ENV + ". 模拟环境数据更新");
            System.out.println(MENU_SEND_COMMAND + ". 下发控制命令");
            System.out.println(MENU_EXIT + ". 退出系统");

            int choice = getValidIntInput(1, 4, "请选择操作（1-4）：");

            switch (choice) {
                case MENU_VIEW_STATUS:
                    showRunningMachines();
                    break;
                case MENU_SIMULATE_ENV:
                    simulateEnvironmentChange();
                    break;
                case MENU_SEND_COMMAND:
                    sendCommand();
                    break;
                case MENU_EXIT:
                    System.out.println("系统退出");
                    return;
            }
        }
    }

    // 仅显示运行中的农机
    private static void showRunningMachines() {
        System.out.println("\n=== 运行中的农机状态 ===");
        boolean hasRunning = false;
        for (FarmMachine machine : machines) {
            if (machine.getState().isRunning()) {  // 关键过滤逻辑
                System.out.println(machine.getType() + " 状态：" + machine.getState().getClass().getSimpleName());
                hasRunning = true;
            }
        }
        if (!hasRunning) {
            System.out.println("当前无运行中的农机");
        }
    }

    private static void simulateEnvironmentChange() {
        System.out.println("\n=== 模拟环境数据更新 ===");
        double moisture = getValidDoubleInput(0, 100, "输入土壤湿度(0-100): ");
        int temp = getValidIntInput(-20, 50, "输入温度(℃，-20到50): ");
        boolean obstacle = getValidIntInput(0, 1, "是否有障碍物(0无/1有): ") == 1;

        EnvironmentData data = new EnvironmentData();
        data.setSoilMoisture(moisture);
        data.setTemperature(temp);
        data.setHasObstacle(obstacle);
        monitor.updateData(data);
    }

    private static void sendCommand() {
        System.out.println("\n=== 下发控制命令 ===");
        int machineIdx = getValidIntInput(1, 2, "选择农机（1-播种机, 2-喷药机）: ") - 1;
        FarmMachine machine = machines.get(machineIdx);

        int cmdType = getValidIntInput(1, 2, "选择命令（1-启动, 2-停止）: ");
        Command command = cmdType == 1 ? new StartCommand() : new StopCommand();
        command.execute(machine);
    }

    // 通用整数输入验证（带范围限制）
    private static int getValidIntInput(int min, int max, String prompt) {
        while (true) {
            try {
                System.out.print(prompt);
                int input = scanner.nextInt();
                scanner.nextLine();  // 清除换行符
                if (input >= min && input <= max) {
                    return input;
                }
                System.out.printf("输入范围无效，请输入%d-%d之间的数字：", min, max);
            } catch (InputMismatchException e) {
                System.out.print("输入格式错误，请输入整数：");
                scanner.nextLine();  // 清除无效输入
            }
        }
    }

    // 通用Double输入验证（带范围限制）
    private static double getValidDoubleInput(double min, double max, String prompt) {
        while (true) {
            try {
                System.out.print(prompt);
                double input = scanner.nextDouble();
                scanner.nextLine();  // 清除换行符
                if (input >= min && input <= max) {
                    return input;
                }
                System.out.printf("输入范围无效，请输入%.1f-%.1f之间的数值：", min, max);
            } catch (InputMismatchException e) {
                System.out.print("输入格式错误，请输入数字：");
                scanner.nextLine();  // 清除无效输入
            }
        }
    }
}